<script setup>
// 在页面中导入相关 api
import { preOrder, saveOrder } from '@/api/index'

import button_confirm_occupancy from '@/static/images/button_confirm_occupancy.png'
import button_confirm from '@/static/images/button_confirm.png'
import { computed, ref } from 'vue'
import ScrollSelect from '@/components/ScrollSelect.vue'
import button_select_date from '@/static/images/button_select_date.png'
import { onLoad } from '@dcloudio/uni-app'
import button_cancel from '@/static/images/button_cancel.png'
// import content_bg_image from '@/static/images/content_bg_image.png'
// import {base64_content_bg2_image} from '@/static/base64'
import button_add from '@/static/images/button_add.png'
import { base64_dialog_bg_image } from '@/static/base64'

// const bg_src = content_bg_image // 背景图片
// const bg_src = base64_content_bg2_image // 背景图片
const bg_src = "https://jkht.wteam.club/file/xiaochenxu/content_bg_image.png" // 背景图片
const bg_dialog_src = base64_dialog_bg_image // 弹窗背景图片
const confirm_book_src = ref(button_confirm_occupancy) // 确认预约按钮图片
const select_date_src = ref(button_select_date) // 选择日期按钮图片
const cancel_src = ref(button_cancel) // 取消按钮图片
const now_pay_src = ref(button_confirm) // 确认支付按钮图片
const help_src = ref(button_add) // 帮助按钮图片
const beShowPayDialog = ref(false) // 是否显示支付弹窗

const startDateSelectValue = ref('') // 开始日期选择值
const endDateSelectValue = ref('') // 结束日期选择值
const startDateHour = ref('') // 开始时间选择值
const startTime = ref({
  hour: '0',
  minute: '0',
}) // 开始时间
const endTime = ref({
  hour: '0',
  minute: '0',
}) // 结束时间
const form = ref({
  name: '',
  type: '',
  age: '',
  userId: '',
}) // 表单
const captchaForm = ref({
  one: '',
  two: '',
  three: '',
  four: '',
  five: '',
  six: '',
}) // 验证码表单
const currentYear = new Date().getFullYear() // 当前年份

// 验证码输入框 refs
const dataNum = ref('0')
const hourNum = ref('0')
const minNum = ref('0')

const oneInput = ref(null)
const twoInput = ref(null)
const threeInput = ref(null)
const fourInput = ref(null)
const fiveInput = ref(null)
const sixInput = ref(null)

// 验证码输入框聚焦状态
const oneInputFocus = ref(false)
const twoInputFocus = ref(false)
const threeInputFocus = ref(false)
const fourInputFocus = ref(false)
const fiveInputFocus = ref(false)
const sixInputFocus = ref(false)

// 开始时间选项
const startTimeOption = ref({
  hour: [
    '00',
    '01',
    '02',
    '03',
    '04',
    '05',
    '06',
    '07',
    '08',
    '09',
    '10',
    '11',
    '12',
    '13',
    '14',
    '15',
    '16',
    '17',
    '18',
    '19',
    '20',
    '21',
    '22',
    '23',
  ],
  minute: ['00', '30'],
})
// 结束时间选项
const endTimeOption = ref({
  hour: [
    '00',
    '01',
    '02',
    '03',
    '04',
    '05',
    '06',
    '07',
    '08',
    '09',
    '10',
    '11',
    '12',
    '13',
    '14',
    '15',
    '16',
    '17',
    '18',
    '19',
    '20',
    '21',
    '22',
    '23',
  ],
  minute: ['00', '30'],
})

// 页面加载
onLoad(() => {
  // 获取当前日期
  const date = new Date()
  const year = date.getFullYear()
  const month = ('0' + (date.getMonth() + 1)).slice(-2)
  const day = ('0' + date.getDate()).slice(-2)
  startDateSelectValue.value = `${year}-${month}-${day}`
  endDateSelectValue.value = `${year}-${month}-${day}`
})

const updateUserPet = ()=>{
  form.value.userId =  wx.getStorageSync('token').userId
  uni.request({
    url: 'https://sharebilliardstcp.wteam.club/macback/updateUserPet',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    data: form.value,

    success(res) {
      console.log('updateUserPet成功', res)
    },
  })
}

// 点击 - 确认预约按钮
const clickConfirmBook = () => {
  // beShowPayDialog.value = true
  SubmitOrderInfoData()

  updateUserPet();
}
// 点击 - 取消按钮
const clickCancel = () => {
  beShowPayDialog.value = false
}
// 点击 - 确认支付按钮
const clickPayNow = () => {
  beShowPayDialog.value = false
  // 跳转预约成功页面
  uni.navigateTo({
    url: '/pages/reserve/success',
  })
}
// 聚焦 - 到下一个输入框
const focusNextInput = (currentInput) => {
  switch (currentInput) {
    case 'one':
      if (captchaForm.value.one.length === 1) {
        oneInputFocus.value = false
        twoInputFocus.value = true
      }
      break
    case 'two':
      if (captchaForm.value.two.length === 1) {
        twoInputFocus.value = false
        threeInputFocus.value = true
      }
      break
    case 'three':
      if (captchaForm.value.three.length === 1) {
        threeInputFocus.value = false
        fourInputFocus.value = true
      }
      break
    case 'four':
      if (captchaForm.value.four.length === 1) {
        fourInputFocus.value = false
        fiveInputFocus.value = true
      }
      break
    case 'five':
      if (captchaForm.value.five.length === 1) {
        fiveInputFocus.value = false
        sixInputFocus.value = true
      }
      break
    case 'six':
      // 最后一个输入框，可以进行下一步操作
      break
  }
}
// 处理退格键
const handleBackspace = (currentInput) => {
  if (event.key === 'Backspace') {
    switch (currentInput) {
      case 'two':
        if (captchaForm.value.two.length === 0) {
          captchaForm.value.one = ''
          twoInputFocus.value = false
          oneInputFocus.value = true
        }
        break
      case 'three':
        if (captchaForm.value.three.length === 0) {
          captchaForm.value.two = ''
          threeInputFocus.value = false
          twoInputFocus.value = true
        }
        break
      case 'four':
        if (captchaForm.value.four.length === 0) {
          captchaForm.value.three = ''
          fourInputFocus.value = false
          threeInputFocus.value = true
        }
        break
      case 'five':
        if (captchaForm.value.five.length === 0) {
          captchaForm.value.four = ''
          fiveInputFocus.value = false
          fourInputFocus.value = true
        }
        break
      case 'six':
        if (captchaForm.value.six.length === 0) {
          captchaForm.value.five = ''
          sixInputFocus.value = false
          fiveInputFocus.value = true
        }
        break
    }
  }
}

// 计算属性 - 开始日期 - 月
const startMonth = computed(() => {
  return startDateSelectValue.value.slice(5, 7)
})
// 计算属性 - 开始日期 - 日
const startDay = computed(() => {
  return startDateSelectValue.value.slice(8, 10)
})
// 计算属性 - 结束日期 - 月
const endMonth = computed(() => {
  return endDateSelectValue.value.slice(5, 7)
})
// 计算属性 - 结束日期 - 日
const endDay = computed(() => {
  return endDateSelectValue.value.slice(8, 10)
})
// 计算属性 - 预约时间 - 区间 如 9:30-12:30
const bookTime = computed(() => {
  return `${startTime.value.hour}:${startTime.value.minute}-${endTime.value.hour}:${endTime.value.minute}`
})
// 计算属性 - 预约时间 - 总时长
const bookTimeLength = computed(() => {
  const start = parseInt(startTime.value.hour) * 60 + parseInt(startTime.value.minute)
  const end = parseInt(endTime.value.hour) * 60 + parseInt(endTime.value.minute)
  return (end - start) / 60
})




// 封装函数，调用 api
const preOrderApi = async (data) => {
  let res = await preOrder(data)
  console.log(res)
}

// 封装函数，调用 api
const saveOrderApi = async (roomId) => {
  let res = await saveOrder(roomId)
  console.log(res)
}

const submitorder = async (orderNo) => {
  var that = this

  let startDate =
    currentYear +
    '/' +
    startMonth.value +
    '/' +
    startDay.value +
    ' ' +
    startTime.value.hour +
    ':' +
    startTime.value.minute

  let endDate =
    currentYear +
    '/' +
    endMonth.value +
    '/' +
    endDay.value +
    ' ' +
    endTime.value.hour +
    ':' +
    endTime.value.minute

  let info = await saveOrder({
    roomId: wx.getStorageSync('global_room_id'),
    payType: 1,
    pkgId: '',
    nightLong: false,
    startTime: startDate,
    endTime: endDate,
    orderNo: orderNo,
    groupPayNo: '',
  })
  console.info('提交订单信息===')
  console.info(info)
  if (info.code == 0) {
    if (info.msg) {
      wx.showToast({
        title: info.msg,
        icon: 'none',
      })

    } else {
      wx.showToast({
        title: '预定成功！',
        icon: 'success',
      })
    }
     uni.setStorageSync("startDate",startDate)
     uni.setStorageSync("endDate",endDate)
    setTimeout(function () {
      // 跳转预约成功页面
      uni.navigateTo({
        url: '/pages/reserve/success',
      })
    }, 1000)
  } else {
    wx.showModal({
      title: '温馨提示',
      content: info.msg,
      showCancel: false,
      confirmText: '确定',
      success(res) {},
    })
  }
}

// 预支付
const SubmitOrderInfoData = async () => {
  console.log('SubmitOrderInfoData')

  let startDate =
    currentYear +
    '/' +
    startMonth.value +
    '/' +
    startDay.value +
    ' ' +
    startTime.value.hour +
    ':' +
    startTime.value.minute

  let endDate =
    currentYear +
    '/' +
    endMonth.value +
    '/' +
    endDay.value +
    ' ' +
    endTime.value.hour +
    ':' +
    endTime.value.minute

  let info = await preOrder({
    roomId: wx.getStorageSync('global_room_id'),
    payType: 1,
    pkgId: '',
    nightLong: false,
    startTime: startDate,
    endTime: endDate,
    preSubmit: false,
    userCardId: '',
  })

  console.info('支付信息===')
  if (info.code == 0) {
    let orderNo = info.data.orderNo
    let price = info.data.payPrice / 100.0
    //选择的是微信支付
    if (price <= 0.0) {
      //订单金额为0元的时候，不走微信支付，直接订单提交
      submitorder(orderNo)
    } else {
      lockWxOrder(info)
    }
  } else {
    wx.showModal({
      title: '温馨提示',
      content: info.msg,
      showCancel: false,
      confirmText: '确定',
      success(res) {},
    })
  }
}

const changeStartTimehour = (sel) => {
  console.log('测试1', sel)
  startTime.value.hour = sel
}
const changeStartTimeminute = (sel) => {
  startTime.value.minute = sel
}

const changeEndTimehour = (sel) => {
  endTime.value.hour = sel
}
const changeEndTimeminute = (sel) => {
  endTime.value.minute = sel
}

const getTimeDifference = () => {
  let startDate = new Date(
    currentYear +
      '-' +
      startMonth.value +
      '-' +
      startDay.value +
      'T' +
      startTime.value.hour +
      ':' +
      startTime.value.minute +
      ':00',
  )
  console.log(
    currentYear +
      '-' +
      startMonth.value +
      '-' +
      startDay.value +
      'T' +
      startTime.value.hour +
      ':' +
      startTime.value.minute +
      ':00',
  )
  let endDate = new Date(
    currentYear +
      '-' +
      endMonth.value +
      '-' +
      endDay.value +
      'T' +
      endTime.value.hour +
      ':' +
      endTime.value.minute +
      ':00',
  )
  // 计算毫秒差
  let diffInMs = endDate - startDate

  // 计算天数差
  let days = Math.floor(diffInMs / (1000 * 60 * 60 * 24))

  // 计算剩余小时数
  let hours = Math.floor((diffInMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))

  // 计算剩余分钟数
  let minutes = Math.floor((diffInMs % (1000 * 60 * 60)) / (1000 * 60))

  console.log(days)
  console.log(hours)
  console.log(minutes)

  dataNum.value = days
  hourNum.value = hours
  minNum.value = minutes

  return {
    days: days,
    hours: hours,
    minutes: minutes,
  }
}
</script>

<template>
  <view class="main" :style="{ backgroundImage: `url(${bg_src})` }">
    <!-- 内容 -->
    <view class="content">
      <!-- 帮助部分 -->
      <view class="help-view">
        <image class="help-button" :src="help_src" mode="heightFix" />
      </view>
      <!-- 选择时间部分 -->
      <view class="select-time">
        <!-- 开始时间日期 -->
        <view class="start-datetime">
          <view class="start-date">
            <uni-datetime-picker v-model="startDateSelectValue" type="date" style="height: 100%">
              <view class="start-date-view">
                <text class="month-text">{{ startMonth }}</text>
                <text class="day-text">{{ startDay }}</text>
                <image class="select-date-button" :src="select_date_src" mode="heightFix" />
              </view>
            </uni-datetime-picker>
          </view>
          <view class="start-time">
            <view class="hour-time">
              <scroll-select
                :columns="startTimeOption.hour"
                @changSelected="changeStartTimehour"
              ></scroll-select>
            </view>
            <view class="minute-time">
              <scroll-select
                :columns="startTimeOption.minute"
                @changSelected="changeStartTimeminute"
              ></scroll-select>
            </view>
          </view>
        </view>
        <!-- 结束时间 -->
        <view class="end-datetime">
          <view class="end-date">
            <uni-datetime-picker v-model="endDateSelectValue" type="date" style="height: 100%">
              <view class="end-date-view">
                <text class="month-text">{{ endMonth }}</text>
                <text class="day-text">{{ endDay }}</text>
                <image class="select-date-button" :src="select_date_src" mode="heightFix" />
              </view>
            </uni-datetime-picker>
          </view>
          <view class="end-time">
            <view class="hour-time">
              <scroll-select
                :columns="endTimeOption.hour"
                @changSelected="changeEndTimehour"
              ></scroll-select>
            </view>
            <view class="minute-time">
              <scroll-select
                :columns="endTimeOption.minute"
                @changSelected="changeEndTimeminute"
              ></scroll-select>
            </view>
          </view>
        </view>
        <!-- 金额 -->
        <view class="money-view">
          <text class="num-text">{{ dataNum }}</text>
          <text class="num-text-mini">天</text>
          <text class="num-text">{{ hourNum }}</text>
          <text class="num-text-mini">小时</text>
        </view>
      </view>
      <!-- 表单内容 -->
      <view class="form-view">
        <input class="input-item" type="text" v-model="form.name" />
        <input class="input-item" type="text" v-model="form.type" />
        <input class="input-item" type="text" v-model="form.age" />
      </view>
      <!-- 确认预约按钮 -->
      <view class="button-view">
        <image
          @click="clickConfirmBook"
          class="confirm-book-button"
          :src="confirm_book_src"
          mode="widthFix"
        />
      </view>
    </view>
    <!-- 支付弹窗 -->
    <view
      v-show="beShowPayDialog"
      class="pay-dialog"
      :style="{ backgroundImage: `url(${bg_dialog_src})` }"
    >
      <view class="dialog-content">
        <view class="cancel-view">
          <image @click="clickCancel" class="cancel-button" :src="cancel_src" mode="heightFix" />
        </view>
        <!-- 验证码 -->
        <view class="captcha-view">
          <input
            class="input-item"
            type="number"
            v-model="captchaForm.one"
            oninput="value=value.replace(/[^\d]/g,'')"
            maxlength="1"
            ref="oneInput"
            @input="focusNextInput('one')"
            :focus="oneInputFocus"
            @keydown="handleBackspace('one')"
          />
          <input
            class="input-item"
            type="number"
            v-model="captchaForm.two"
            maxlength="1"
            ref="twoInput"
            @input="focusNextInput('two')"
            :focus="twoInputFocus"
            @keydown="handleBackspace('two')"
          />
          <input
            class="input-item"
            type="number"
            v-model="captchaForm.three"
            maxlength="1"
            ref="threeInput"
            @input="focusNextInput('three')"
            :focus="threeInputFocus"
            @keydown="handleBackspace('three')"
          />
          <input
            class="input-item"
            type="number"
            v-model="captchaForm.four"
            maxlength="1"
            ref="fourInput"
            @input="focusNextInput('four')"
            :focus="fourInputFocus"
            @keydown="handleBackspace('four')"
          />
          <input
            class="input-item"
            type="number"
            v-model="captchaForm.five"
            maxlength="1"
            ref="fiveInput"
            @input="focusNextInput('five')"
            :focus="fiveInputFocus"
            @keydown="handleBackspace('five')"
          />
          <input
            class="input-item"
            type="number"
            v-model="captchaForm.six"
            maxlength="1"
            ref="sixInput"
            @input="focusNextInput('six')"
            :focus="sixInputFocus"
            @keydown="handleBackspace('six')"
          />
        </view>
        <view class="time-view">
          <text class="interval-text">30S</text>
        </view>
        <view class="confirm-view">
          <image @click="clickPayNow" class="pay-now-button" :src="now_pay_src" mode="widthFix" />
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.main {
  display: flex;
  flex-direction: column;
  height: 100vh;
  // 背景图片自适应
  background-size: 100% 100%;
  position: relative;

  // 内容
  .content {
    flex: 1;
    overflow: auto;
    padding: 45rpx 30rpx 35rpx;

    // 帮助部分
    .help-view {
      height: 5.5%;
      padding: 3%;

      .help-button {
        height: 42rpx;
        float: right;
      }
    }

    // 选择时间部分
    .select-time {
      height: 60%;

      // 开始时间日期
      .start-datetime {
        height: 50%;
        padding-top: 17%;

        // 开始日期
        .start-date {
          height: 18%;
          margin-bottom: 1.8%;

          :deep(.uni-date-editor) {
            height: 100%;
          }

          .start-date-view {
            height: 100%;
            display: flex;

            .month-text {
              font-size: 36rpx;
              margin-left: 45%;
              // 水平居中
              text-align: center;
            }

            .day-text {
              font-size: 36rpx;
              margin-left: 10%;
            }

            .select-date-button {
              height: 100%;
              margin-left: 3%;
            }
          }
        }

        // 开始时间
        .start-time {
          height: 68%;
          display: flex;

          .hour-time {
            width: 100rpx;
            height: 100%;
            margin-left: 25%;
          }

          .minute-time {
            width: 100rpx;
            height: 100%;
            margin-left: 15%;
          }
        }
      }

      // 结束时间
      .end-datetime {
        height: 35.5%;
        padding-top: 3%;

        // 结束日期
        .end-date {
          height: 19.5%;
          margin-bottom: 1.8%;

          :deep(.uni-date-editor) {
            height: 100%;
          }

          .end-date-view {
            height: 100%;
            display: flex;

            .month-text {
              font-size: 36rpx;
              margin-left: 45%;
            }

            .day-text {
              font-size: 36rpx;
              margin-left: 10%;
            }

            .select-date-button {
              height: 100%;
              margin-left: 3%;
            }
          }
        }

        // 结束时间
        .end-time {
          height: 77%;
          display: flex;

          .hour-time {
            width: 100rpx;
            height: 100%;
            margin-left: 25%;
          }

          .minute-time {
            width: 100rpx;
            height: 100%;
            margin-left: 15%;
          }
        }
      }

      // 金额 元素居中
      .money-view {
        margin-top: 3%;
        height: 10%;
        display: flex;
        margin-left: 48%;
        align-items: flex-end;

        .sign-text {
          font-size: 30rpx;
          color: white;
        }

        .num-text {
          font-size: 70rpx;
          color: white;
          // 向上偏移
          margin-top: -3%;
        }

        .num-text-mini {
          font-size: 30rpx;
          color: white;
          margin-bottom: 5px;
        }
      }
    }

    // 表单内容
    .form-view {
      height: 12.8%;
      margin-top: 7.5%;

      // 输入框
      .input-item {
        width: 100%;
        height: 28%;
        margin-bottom: 2.4%;
        padding-left: 35%;
        color: rgb(27, 64, 124);
        font-size: 36rpx;
      }
    }

    // 确认预约按钮
    .button-view {
      height: calc(100% - 5.5% - 60% - 12.8% - 7.5%);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .confirm-book-button {
        width: 80%;
      }
    }
  }

  // 支付弹窗
  .pay-dialog {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-size: 100% 100%;

    // 弹窗内容
    .dialog-content {
      width: 100%;
      height: 45%;
      margin-top: 58%;

      // 取消按钮
      .cancel-view {
        height: 10%;

        .cancel-button {
          height: 100%;
          float: right;
          margin-right: 3%;
        }
      }

      // 验证码
      .captcha-view {
        margin-top: 39%;
        height: 7.5%;
        padding: 0 27.2% 0 27.8%;
        display: flex;
        justify-content: center;
        align-items: center;

        .input-item {
          width: 12.5%;
          height: 100%;
          margin-right: 5.5%;
          color: rgb(27, 64, 124);
          font-size: 36rpx;
          text-align: center;
        }

        // 最后一个输入框不需要margin
        .input-item:last-child {
          margin-right: 0;
        }
      }

      // 预约时间
      .time-view {
        margin-top: 4%;
        height: 5%;

        .interval-text {
          line-height: 100%;
          height: 100%;
          font-size: 24rpx;
          color: white;
          margin-left: 50%;
        }

        .total-text {
          font-size: 30rpx;
          color: white;
          margin-left: 6%;
        }
      }

      // 确认支付按钮
      .confirm-view {
        height: 30%;
        // 按钮居中
        display: flex;
        justify-content: center;
        align-items: center;

        .pay-now-button {
          width: 80%;
        }
      }
    }
  }
}
</style>
